package org.app.Config;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.alibaba.fastjson.JSONObject;

import org.apache.shiro.subject.Subject;
import org.app.Entity.Auth.CustomPrincipal;
import org.app.Entity.User;
import org.app.Exception.BizException;
import org.app.Service.IAuthService;
import org.app.Service.IUserService;
import org.app.Utils.JwtUtil;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class AppRealm extends AuthorizingRealm {
    @Resource
    private IAuthService authService;
    @Resource
    private IUserService userService;
    /**
     * 默认使用的token为：{@link org.apache.shiro.authc.UsernamePasswordToken}
     * ，所以需要重写support方法，不然会报错token不匹配
     * <p>或者在realm中设置authenticationTokenClass属性为你想要使用的Token</p>
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        CustomPrincipal customPrincipal = (CustomPrincipal) principalCollection.getPrimaryPrincipal();
        CustomPrincipal customPrincipal= (CustomPrincipal) principalCollection.getPrimaryPrincipal();
        User user = customPrincipal.getUser();
//        System.out.println(user);
//                从URL中获取group_id
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        String group_id = request.getParameter("group_id");
//         如果 URL 参数中没有 group_id，再从请求 body 中获取
//        if (group_id == null || group_id.isEmpty()) {
//            try {
////                group_id = request.getBodyGroupId((HttpServletRequest) request);
//
//                if (group_id == null || group_id.isEmpty()) {
//                    throw new BizException("请求体中缺少 group_id");
//                }
//            }
//            catch (IOException e) {
//                throw new BizException("无法读取请求体", e);
//            }
//        }
        //用户权限列表
        Set<String> permsSet = authService.getUserPermissions(user.getC_id());

//        //用户角色列表
//        Set<String> rolesSet = authService.getUserRoles(user.getC_id(),group_id);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
//        info.setRoles(rolesSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {

        JWTToken jwtToken = (JWTToken) authenticationToken;
        SimpleAuthenticationInfo info = null;
        String token = jwtToken.getPrincipal();
        String userId;
        try {
            DecodedJWT parse = JwtUtil.verify(token);
            userId = parse.getClaim("c_id").asString();
        } catch (JWTVerificationException e) {
            throw new JWTVerificationException("过期的token");
        }
        User user = userService.selectUserById(userId).getData();
        if (user == null) {
            throw new BizException("没有该用户");
        }

//        CustomPrincipal customPrincipal = new CustomPrincipal(user, null);
        info = new SimpleAuthenticationInfo(user, token, getName());
        return info;
    }
}